import {
    _decorator,
    Component,
    director,
    sys,
    Label,
    Sprite,
    resources,
    SpriteFrame,
    ImageAsset,
    assetManager,
    Texture2D,
    Node
} from 'cc';
import {GlobalConst} from "db://assets/scripts/consts/GlobalConst";
import {get, post} from "db://assets/scripts/config/Api";
import {WxUser} from "db://assets/scripts/dto/WxUser";
import {AudioMgr} from "db://assets/scripts/component/AudioMgr";
import {WebsocketMgr} from "db://assets/scripts/component/WebsocketMgr";
import {SocketMessage} from "db://assets/scripts/dto/SocketMessage";
import {SocketLogicInterface} from "db://assets/scripts/interface/SocketLogicInterface";
import {RoofInfoDTO} from "db://assets/scripts/dto/RoofInfoDTO";
import {Palette} from "db://assets/scripts/component/Palette";
import {levelEnumInfo, LevelInfo} from "db://assets/scripts/consts/Game2048LevelEnum";
import {Lv2048Tg} from "db://assets/scripts/component/Lv2048Tg";

const {ccclass, property} = _decorator;

const wx = window['wx'];

@ccclass('Home')
export class Home extends Component implements SocketLogicInterface {


    @property(Label)
    userNickNameLabel: Label = null!;

    @property(Sprite)
    userHead: Sprite = null!;

    userInfo: WxUser;

    @property(Node)
    gamePanel: Node = null!;

    @property(Node)
    mePanel: Node = null!;


    @property(Node)
    marsk: Node = null!;

    @property(Node)
    gamePending: Node = null!;
    @property(Label)
    gamePendingText: Label = null!;

    gameType: string = null;

    @property(Lv2048Tg)
    userLvNode: Lv2048Tg = null!;


    async start() {

        this.gamePanel.active = true;
        this.mePanel.active = false;

        this.test();
        await this.login();
        //this.getUserInfo();
        this.subscription();
        wx.showShareMenu({
            menus: ['shareAppMessage', 'shareTimeline']
        })
        wx.onShareAppMessage(() => {
            return {
                title: "快来与我一起玩竞技版2048吧！",
            }
        })
        wx.onShareTimeline(() => {
            return {
                title: "快来与我一起玩竞技版2048吧！",
            }
        })
        this.isJoinRoom();


    }

    update(deltaTime: number) {

    }

    subscription() {
        console.log("订阅消息")

        WebsocketMgr.inst.socketLogic.set(this.getPatch(), this);
        WebsocketMgr.inst.reconnectFailMessage.set(this, this.reconnectFail);
    }

    getPatch(): string {
        return "home";
    }

    private click2048() {
        console.log("2048")
        director.loadScene("game2048")
    }

    private test() {
        if (wx == null) {
            sys.localStorage.setItem('token', "0980acd5-61bc-4da5-89d6-3c7517f95dd7");
            sys.localStorage.setItem('userInfo', "{\n" +
                "    \"createTime\": \"2025-03-14 10:54:01.915561431\",\n" +
                "    \"game2048Level\": \"LV1\",\n" +
                "    \"game2048MaxScore\": 2028,\n" +
                "    \"gameXiaoxiaoMaxScore\": 0,\n" +
                "    \"id\": 142,\n" +
                "    \"session\": {\n" +
                "        \"openid\": \"oKyVy7c4AwGy3q3pscEtQRDSjeR4\",\n" +
                "        \"session_key\": \"Cb0rMYBzrIKTiMxhnweHzQ==\"\n" +
                "    },\n" +
                "    \"star\": 0,\n" +
                "    \"wxHead\": \"https://hq-store.oss-cn-shanghai.aliyuncs.com/upload/20250314/96daad1eac6544f490f4349a8b2fde83.userHeaderoKyVy7c4AwGy3q3pscEtQRDSjeR4.png\",\n" +
                "    \"wxId\": \"oKyVy7c4AwGy3q3pscEtQRDSjeR4\",\n" +
                "    \"wxUsername\": \"逍遥\"\n" +
                "}");

        }
    }

    private xiaoxiaole() {
        console.log("消消乐")
        director.loadScene("xiaoxiaole")
    }

    private login(): Promise<any> {

        return new Promise(async (resolve, reject) => {
            if (sys.localStorage.getItem("userInfo") != null
                && sys.localStorage.getItem("userInfo") !== ''
                && sys.localStorage.getItem("userInfo") !== 'null'
                && JSON.parse(sys.localStorage.getItem("userInfo")).wxUsername
            ) {
                console.log("已经有用户信息,不再登录", sys.localStorage.getItem("userInfo"))
                this.userInfo = JSON.parse(sys.localStorage.getItem("userInfo"));
                console.log("store获取用户信息", this.userInfo);
                let isVaild = await get<boolean>("/wx/tokenEffective", {
                    token: sys.localStorage.getItem("token")
                });
                if (isVaild) {
                    WebsocketMgr.inst.initSocket();
                    this.getMe(sys.localStorage.getItem("token"));
                    resolve(null);
                    return
                } else {
                    sys.localStorage.removeItem("token");
                    sys.localStorage.removeItem("userInfo");
                    console.log("token失效,重新登录");
                    return this.login();

                }

            }


            wx.login({
                success: async (res) => {
                    if (res.code) {
                        //发起网络请求
                        wx.request({
                            url: GlobalConst.api + "/wx/wxLogin/" + res.code,
                            method: "GET",
                            success: async (res) => {
                                console.log("登录成功", res);
                                let token = res.data.data;
                                console.log("设置用户token", token)
                                sys.localStorage.setItem('token', token);
                                WebsocketMgr.inst.initSocket();
                                await this.getMe(token);
                                this.getUserInfo();
                                resolve(null);

                            }

                        })
                    } else {
                        reject(res.errMsg);
                        console.log('登录失败！' + res.errMsg)
                    }
                }
            })
        })


    }


    private async getMe(token: string) {
        let resultMe = await get<WxUser>("/wx/me");
        sys.localStorage.setItem('userInfo', JSON.stringify(resultMe));
        this.userInfo = JSON.parse(sys.localStorage.getItem("userInfo"));
        this.showUserInfo();
    }


    private getUserInfo() {
        if (wx == null) {
            return;
        }
        console.log("获取用户信息")
        console.log(this.userInfo.wxHead)
        if (this.userInfo.wxHead != '') {
            return;
        }
        console.log("隐私协议授权")
        wx.getSetting({
            success: (res) => {
                if (res.authSetting['scope.userInfo']) {
                    console.log("已经授权直接调用getUserInfo");
                    wx.getUserInfo({
                        success: (res) => {
                            console.log("获取用户信息成功", res)
                            this.setUserInfo(res.userInfo);
                        }
                    })
                } else {
                    console.log('先同意隐私协议');
                    wx.requirePrivacyAuthorize({
                        success: res => {
                            console.log("原因", res);
                            /*   let info = wx.getSystemInfoSync();
                               let button = wx.createUserInfoButton({
                                   type: 'text',
                                   text: '点击获取用户信息',
                                   style: {
                                       left: info.screenWidth / 2 - 100,
                                       top: 300,
                                       width: 200,
                                       height: 40,
                                       lineHeight: 40,
                                       backgroundColor: '#8D99D5',
                                       color: '#ffffff',
                                       textAlign: 'center',
                                       fontSize: 16,
                                       borderRadius: 4
                                   }
                               })
                               button.onTap((res) => {
                                   console.log("结果::", res.userInfo);

                                   button.hide();
                                   this.setUserInfo(res.userInfo);
                               })*/
                        }
                    })

                }
            }
        })
    }

    private async setUserInfo(userInfo: {
        avatarUrl: string;
        nickName: string;
    }) {
        console.log("用户头像" + userInfo.avatarUrl);
        console.log("用户昵称" + userInfo.nickName);
        let res = await post("/wx/updateUser", {
            "nickName": userInfo.nickName,
            "headUrl": userInfo.avatarUrl,
        })

        await this.getMe(sys.localStorage.getItem("token"));
    }


    private async createGetUserNickName(cal: (userInfo: {
        avatarUrl: string;
        nickName: string;
    }) => void) {
        this.marsk.active = true;
        let info = wx.getSystemInfoSync();
        let button = wx.createUserInfoButton({
            type: 'text',
            text: '点击获取用户信息',
            style: {
                left: info.screenWidth / 2 - 100,
                top: 300,
                width: 200,
                height: 40,
                lineHeight: 40,
                backgroundColor: '#1135e3',
                color: '#ffffff',
                textAlign: 'center',
                fontSize: 16,
                borderRadius: 4
            }
        })
        button.onTap(async (res) => {
            console.log("结果::", res.userInfo);
            button.hide();
            this.marsk.active = false;
            await this.setUserInfo(res.userInfo);
            cal(res.userInfo);
        })
    }


    private showUserInfo() {
        console.log(this.userInfo)
        if (!this.userInfo
            || !this.userInfo.wxUsername) {

            this.userNickNameLabel.string = "获取用户信息";
            resources.load("imgs/wxHead/spriteFrame", SpriteFrame, (err, spriteFrame) => {
                this.userHead.spriteFrame = spriteFrame;
            });
            return;
        }
        console.log("当前用户信息", this.userInfo)
        this.userNickNameLabel.string = this.userInfo.wxUsername;
        // 从url设置头像
        assetManager.loadRemote<ImageAsset>(this.userInfo.wxHead, (err, imageAsset) => {
            const spriteFrame = new SpriteFrame();
            const texture = new Texture2D();
            texture.image = imageAsset;
            spriteFrame.texture = texture;
            this.userHead.spriteFrame = spriteFrame;
        });


        this.userLvNode.init(this.userInfo.game2048Level);


        //获取颜色
    }

    private clickGamePanel() {
        this.gamePanel.active = true;
        this.mePanel.active = false;
    }

    private clickMePanel() {
        this.mePanel.active = true;
        this.gamePanel.active = false;
    }

    private match(event: Event, gameType: string) {

        if (!this.userInfo.wxHead) {
            this.gameType = gameType;
            this.createGetUserNickName((userInfo) => {
                if (this.gameType!) {
                    this.match(null, this.gameType)
                }
                this.gameType = null;
            });
            return
        }
        if (this.gamePending.active) {
            return;
        }
        // 匹配的文案
        let socketMessag: SocketMessage = new SocketMessage();
        socketMessag.event = "match";
        socketMessag.data = gameType;
        WebsocketMgr.inst.sendMessage(socketMessag);

        this.gamePending.active = true;
        this.gamePendingText.string = "匹配中.";
        this.schedule(() => {
            // 这里的 this 指向 component
            if (this.gamePendingText.string === "匹配中...") {
                this.gamePendingText.string = "匹配中."
                return;
            }
            this.gamePendingText.string += ".";
        }, 1);
    }

    accept(message: SocketMessage) {
        let events = message.event.split('/');
        // 等待
        if (events[1] === "matchPending") {
            this.matchPending(message);
            return;
        } else if (events[1] === "matchSuccess") {
            this.matchSuccess(message);
            return;
        } else if (events[1] === "createRoomSuccess") {
            this.createRoomInfoSuccess(message);
            return;
        }
    }

    private matchPending(message: SocketMessage) {
        console.log("等待中");
    }

    private matchSuccess(message: SocketMessage) {
        console.log("匹配成功");
        let roofInfo: RoofInfoDTO = message.data as RoofInfoDTO;
        sys.localStorage.setItem("roofInfo", JSON.stringify(message.data));
        this.deSubscription();
        if (roofInfo.status === 0) {
            director.loadScene("GameRoom")
            return;
        }

        if (message.data?.gameType === "2048") {
            director.loadScene("gameMany2048")
        } else {
            director.loadScene("xiaoxiaoleManey")
        }
    }

    deSubscription() {
        console.log("取消订阅消息")
        WebsocketMgr.inst.socketLogic.delete(this.getPatch());
        WebsocketMgr.inst.reconnectFailMessage.delete(this);
    }

    public clickClearStore() {
        console.log("清除缓存")
        sys.localStorage.removeItem("roofInfo");
        sys.localStorage.removeItem("token");
        sys.localStorage.removeItem("userInfo");
        sys.localStorage.removeItem("roomId");

    }

    private reconnectFail() {
        WebsocketMgr.inst.reconnectAttempts = 0;
        // 首页继续重连
        WebsocketMgr.inst.reconnect();
    }

    private cancelMatch() {
        this.unscheduleAllCallbacks();
        this.gamePending.active = false;
        let socketMessag: SocketMessage = new SocketMessage();
        socketMessag.event = "cancelMatch";
        WebsocketMgr.inst.sendMessage(socketMessag);
    }

    private createRoom(event: Event, gameType: string) {
        if (!this.userInfo.wxHead) {
            this.createGetUserNickName((userInfo) => {
                this.createRoom(null, this.gameType);
            });
            return;
        }

        let socketMessag: SocketMessage = new SocketMessage();
        socketMessag.event = "createRoom";
        let createRoomInfoDTO = {
            gameType: gameType,
        }
        socketMessag.data = createRoomInfoDTO;
        WebsocketMgr.inst.sendMessage(socketMessag);
    }

    private createRoomInfoSuccess(message: SocketMessage) {
        console.log("创建房间成功");
        sys.localStorage.setItem("roofInfo", JSON.stringify(message.data));
        director.loadScene("GameRoom")
    }

    private isJoinRoom() {
        let option = wx.getLaunchOptionsSync();
        console.log("当前进入roomid", option.query?.roomId);
        console.log("缓存roomid", sys.localStorage.getItem("roomId"));
        if (option.query && option.query.roomId
            && (
                sys.localStorage.getItem("roomId") == null
                || sys.localStorage.getItem("roomId") != option.query.roomId
            )) {

            if (WebsocketMgr.inst.isOnline === 1) {
                console.log("加入房间", option.query.roomId)
                sys.localStorage.setItem("roomId", option.query.roomId);
                sys.localStorage.removeItem("roofInfo");
                director.loadScene("GameRoom");
            } else {
                setTimeout(() => {
                        this.isJoinRoom();
                    }
                    , 300)
            }

        }
    }
}


